using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ICP_MS.Plugin.LA300;

public class ExperimentDatas
{
	public const int AcqInterval = 2;

	private List<AnalyteIsotope> selectIsotopes = new List<AnalyteIsotope>();

	private IList<ScanRegions> surveyRegions = new List<ScanRegions>();

	private IList<ScanRegions> scanRegions = new List<ScanRegions>();

	private List<PeakRegions> peakRegions = new List<PeakRegions>();

	private List<IsotopeInfos> isotopes = new List<IsotopeInfos>();

	private List<IsotopeRatio> ratios = new List<IsotopeRatio>();

	private List<SamplesInfos> samples = new List<SamplesInfos>();

	private List<StandardConcentration> stdConcentration = new List<StandardConcentration>();

	private List<AnalyseInfos> results = new List<AnalyseInfos>();

	private List<StatisticResults> statistics = new List<StatisticResults>();

	private List<RatioResults> ratioResults = new List<RatioResults>();

	private List<RatioStatistics> ratioStat = new List<RatioStatistics>();

	private List<SpectrumInfos> spectrums = new List<SpectrumInfos>();

	private List<IsotopeCurve> curves = new List<IsotopeCurve>();

	private ReportParams reportParams = new ReportParams
	{
		ShowRuns = true,
		ShowMean = true,
		ShowSd = true,
		ShowRsd = true,
		ShowConc = true,
		ShowCPS = true,
		ShowUCPS = true,
		ShowCurve = true,
		Header = Lang.Txt("AddFormReport.CompanyName"),
		Title = Lang.Txt("AddFormReport.Title"),
		Logo = null
	};

	private ScanParams scanParams = new ScanParams();

	private IList<PointF> disallowedRanges = new List<PointF>();

	private List<SampleISTD> sampleIstds = new List<SampleISTD>();

	private List<IntegerRegions> integerRegions = new List<IntegerRegions>();

	private List<TimeSpectrum> timeSpectrums = new List<TimeSpectrum>();

	private List<AcqTime> acqTimes = new List<AcqTime>();

	private AutoResetEvent scanEvent = new AutoResetEvent(initialState: false);

	private string internalSchema = "Default";

	private bool isInCalculate = false;

	private DirtyInfo dirty = new DirtyInfo();

	private double[][] surveyMass = null;

	private double[] scanMass = null;

	private double[] peakMass = null;

	private int[] resolutionType = null;

	public Platform CurrentPlat { get; set; }

	public X2Lens CurrentLens { get; set; }

	public PlasmaPara CurrentPlasma { get; set; }

	public RFS CurrentRFS { get; set; }

	public Injector CurrentInjector { get; set; }

	public StableConfig StableConfig { get; set; }

	public List<AnalyteIsotope> SelectIsotopes
	{
		get
		{
			return selectIsotopes;
		}
		set
		{
			selectIsotopes = value;
		}
	}

	public IList<ScanRegions> SurveyRegions
	{
		get
		{
			return surveyRegions;
		}
		set
		{
			surveyRegions = value;
		}
	}

	public IList<ScanRegions> ScanRegions
	{
		get
		{
			return scanRegions;
		}
		set
		{
			scanRegions = value;
		}
	}

	public List<PeakRegions> PeakRegions
	{
		get
		{
			return peakRegions;
		}
		set
		{
			peakRegions = value;
		}
	}

	public List<IsotopeInfos> Isotopes
	{
		get
		{
			return isotopes;
		}
		set
		{
			isotopes = value;
		}
	}

	public List<IsotopeRatio> Ratios
	{
		get
		{
			return ratios;
		}
		set
		{
			ratios = value;
		}
	}

	public List<SamplesInfos> Samples
	{
		get
		{
			return samples;
		}
		set
		{
			samples = value;
		}
	}

	public List<StandardConcentration> StdConcentration
	{
		get
		{
			return stdConcentration;
		}
		set
		{
			stdConcentration = value;
		}
	}

	public List<AnalyseInfos> Results
	{
		get
		{
			return results;
		}
		set
		{
			results = value;
		}
	}

	public List<StatisticResults> Statistics
	{
		get
		{
			return statistics;
		}
		set
		{
			statistics = value;
		}
	}

	public List<RatioResults> RatioResults
	{
		get
		{
			return ratioResults;
		}
		set
		{
			ratioResults = value;
		}
	}

	public List<RatioStatistics> RatioStat
	{
		get
		{
			return ratioStat;
		}
		set
		{
			ratioStat = value;
		}
	}

	public List<SpectrumInfos> Spectrums
	{
		get
		{
			return spectrums;
		}
		set
		{
			spectrums = value;
		}
	}

	public List<IsotopeCurve> Curves
	{
		get
		{
			return curves;
		}
		set
		{
			curves = value;
		}
	}

	public ReportParams ReportParams
	{
		get
		{
			return reportParams;
		}
		set
		{
			reportParams = value;
		}
	}

	public ScanParams Scan
	{
		get
		{
			return scanParams;
		}
		set
		{
			scanParams = value;
		}
	}

	public IList<PointF> DisallowedRanges => disallowedRanges;

	public List<SampleISTD> SampleIstds => sampleIstds;

	public List<IntegerRegions> IntegerRegions => integerRegions;

	public List<TimeSpectrum> TimeSpectrums => timeSpectrums;

	public List<AcqTime> AcqTimes => acqTimes;

	public string InternalSchema
	{
		get
		{
			return internalSchema;
		}
		set
		{
			internalSchema = value;
		}
	}

	public DirtyInfo Dirty => dirty;

	public bool IsRun { get; set; }

	public event EventHandler<ExperimentEventArgs> EventExperiment = null;

	public event EventHandler applyEnable = null;

	public event EventHandler<CurveInfoEventArgs> SingleAcq = null;

	public event EventHandler isotopeChanged = null;

	public event EventHandler istdChanged = null;

	public event EventHandler sampleChanged = null;

	public event EventHandler methodChanged = null;

	public void SortIsotopes()
	{
		Isotopes.Sort((IsotopeInfos isotope1, IsotopeInfos isotope2) => isotope1.mass.CompareTo(isotope2.mass));
	}

	public void SetupIsotopeInfos()
	{
		Isotopes.RemoveAll((IsotopeInfos isotope) => !SelectIsotopes.Exists((AnalyteIsotope selectIsotope) => selectIsotope.symbol == isotope.symbol));
		SelectIsotopes.ForEach(delegate(AnalyteIsotope selectIsotope)
		{
			if (!Isotopes.Exists((IsotopeInfos isotope) => isotope.symbol == selectIsotope.symbol))
			{
				Isotopes.Add(new IsotopeInfos
				{
					id = selectIsotope.id,
					symbol = selectIsotope.symbol,
					mass = selectIsotope.mass,
					name = "Default",
					units = "ppb",
					visible = true,
					technique = Lang.Txt("AddFormIsotopes.None"),
					force = 0,
					withInterference = selectIsotope.withInterference,
					isInterference = false
				});
			}
			else
			{
				IsotopeInfos isotopeInfos = Isotopes.Find((IsotopeInfos isotope) => isotope.symbol == selectIsotope.symbol);
				isotopeInfos.isInterference = false;
			}
		});
		Dirty.IsotopeInfoDirty = true;
	}

	public void UpdateResultsBySampleId(SamplesInfos sample)
	{
		Results.RemoveAll((AnalyseInfos r) => r.sampleId == sample.guid);
		Statistics.RemoveAll((StatisticResults r) => r.sampleId == sample.guid);
		foreach (IsotopeInfos isotope in Isotopes)
		{
			for (int num = 0; num < sample.mains; num++)
			{
				Results.Add(new AnalyseInfos
				{
					isotopeId = isotope.id,
					symbol = isotope.symbol,
					sampleId = sample.guid,
					label = sample.label,
					number = num,
					test = false,
					intensity = -1.0,
					concentration = -1.0,
					icps = -1.0
				});
			}
			Statistics.Add(new StatisticResults
			{
				isotopeId = isotope.id,
				symbol = isotope.symbol,
				sampleId = sample.guid,
				label = sample.label,
				avgCon = -1.0,
				avgUICPS = -1.0,
				avgCPS = -1.0,
				sdCon = -1.0,
				sdUICPS = -1.0,
				sdCPS = -1.0,
				rsdCon = -1.0,
				rsdUICPS = -1.0,
				rsdCPS = -1.0,
				include = true
			});
		}
	}

	public void SetupResultsBySample()
	{
		IEnumerable<int> sampleIds = Samples.Select((SamplesInfos sample) => sample.guid);
		Results.RemoveAll((AnalyseInfos r) => !sampleIds.Contains(r.sampleId));
		Statistics.RemoveAll((StatisticResults r) => !sampleIds.Contains(r.sampleId));
		RatioResults.RemoveAll((RatioResults r) => !sampleIds.Contains(r.SampleId));
		RatioStat.RemoveAll((RatioStatistics r) => !sampleIds.Contains(r.SampleId));
		IEnumerable<int> r_sampleId = Results.Select((AnalyseInfos result) => result.sampleId);
		foreach (SamplesInfos sample2 in Samples)
		{
			if (r_sampleId.Contains(sample2.guid))
			{
				continue;
			}
			foreach (IsotopeInfos isotope2 in Isotopes)
			{
				for (int num2 = 0; num2 < sample2.mains; num2++)
				{
					Results.Add(new AnalyseInfos
					{
						isotopeId = isotope2.id,
						symbol = isotope2.symbol,
						sampleId = sample2.guid,
						label = sample2.label,
						number = num2,
						test = false,
						intensity = -1.0,
						concentration = -1.0,
						icps = -1.0
					});
				}
				Statistics.Add(new StatisticResults
				{
					isotopeId = isotope2.id,
					symbol = isotope2.symbol,
					sampleId = sample2.guid,
					label = sample2.label,
					avgCon = -1.0,
					avgUICPS = -1.0,
					avgCPS = -1.0,
					sdCon = -1.0,
					sdUICPS = -1.0,
					sdCPS = -1.0,
					rsdCon = -1.0,
					rsdUICPS = -1.0,
					rsdCPS = -1.0,
					include = true
				});
			}
			foreach (IsotopeRatio isotope in Ratios)
			{
				ratioStat.Add(new RatioStatistics
				{
					Name = isotope.Name,
					Numerator = isotope.NumeratorSym,
					Denominator = isotope.DenominatorSym,
					SampleId = sample2.guid,
					Label = sample2.label,
					Sd = -1.0,
					Rsd = -1.0,
					Avg = -1.0
				});
				for (int num = 0; num < sample2.mains; num++)
				{
					ratioResults.Add(new RatioResults
					{
						Name = isotope.Name,
						Numerator = isotope.NumeratorSym,
						Denominator = isotope.DenominatorSym,
						SampleId = sample2.guid,
						Label = sample2.label,
						Number = num,
						Result = -1.0
					});
				}
			}
		}
	}

	public void FillStdConcentration()
	{
		StdConcentration.RemoveAll((StandardConcentration std) => !Samples.Exists((SamplesInfos sample) => sample.guid == std.sample) || !Isotopes.Exists((IsotopeInfos isotope) => isotope.symbol.Contains(std.symbol)));
		foreach (SamplesInfos sample2 in Samples)
		{
			if (sample2.type != 1 && sample2.type != 2)
			{
				continue;
			}
			foreach (IsotopeInfos isotope2 in Isotopes)
			{
				if (!StdConcentration.Exists((StandardConcentration std) => std.sample == sample2.guid && isotope2.symbol.Contains(std.symbol)))
				{
					StandardConcentration standard = new StandardConcentration
					{
						label = sample2.label,
						symbol = Regex.Replace(isotope2.symbol, "[0-9]", "", RegexOptions.IgnoreCase),
						inter = isotope2.inter,
						sample = sample2.guid,
						concentration = -1.0,
						method = isotope2.method
					};
					StdConcentration.Add(standard);
				}
			}
		}
	}

	public void SetupRatioResults()
	{
		IEnumerable<string> names = Ratios.Select((IsotopeRatio isotope) => isotope.Name);
		ratioResults.RemoveAll((RatioResults r) => !names.Contains(r.Name));
		RatioStat.RemoveAll((RatioStatistics r) => !names.Contains(r.Name));
		IEnumerable<string> r_names = ratioResults.Select((RatioResults result) => result.Name);
		foreach (IsotopeRatio isotope2 in Ratios)
		{
			if (r_names.Contains(isotope2.Name))
			{
				continue;
			}
			foreach (SamplesInfos sample in Samples)
			{
				ratioStat.Add(new RatioStatistics
				{
					Name = isotope2.Name,
					Numerator = isotope2.NumeratorSym,
					Denominator = isotope2.DenominatorSym,
					SampleId = sample.guid,
					Label = sample.label,
					Sd = -1.0,
					Rsd = -1.0,
					Avg = -1.0
				});
				for (int num = 0; num < sample.mains; num++)
				{
					ratioResults.Add(new RatioResults
					{
						Name = isotope2.Name,
						Numerator = isotope2.NumeratorSym,
						Denominator = isotope2.DenominatorSym,
						SampleId = sample.guid,
						Label = sample.label,
						Number = num,
						Result = -1.0
					});
				}
			}
		}
	}

	private bool InitRunMass()
	{
		List<double> tmp = new List<double>();
		List<int> res = new List<int>();
		foreach (PeakRegions region in PeakRegions)
		{
			tmp.Add(region.mass);
			res.Add((region.resolution == Lang.Txt("ADDTune.TuneDebug.Normal")) ? 1 : ((!(region.resolution == Lang.Txt("ADDTune.TuneDebug.High"))) ? 2 : 0));
			RFManager.rfs.dwell = region.dwell;
		}
		Detector.Instance.msDetectorRF.SetDwell();
		peakMass = tmp.ToArray();
		resolutionType = res.ToArray();
		return true;
	}

	private void InitCurve()
	{
		foreach (IsotopeInfos isotope in Isotopes)
		{
			if (!Curves.Exists((IsotopeCurve curve) => isotope.symbol == curve.symbol))
			{
				Curves.Add(new IsotopeCurve
				{
					isotopeId = isotope.id,
					symbol = isotope.symbol,
					k = 1.0,
					b = 0.0,
					r = 1.0,
					intercept1 = 0.0,
					intercept2 = 0.0,
					calculated = false
				});
			}
		}
	}

	private void InitResult(SamplesInfos sample)
	{
		Results.RemoveAll((AnalyseInfos result) => result.sampleId == sample.guid);
		Statistics.RemoveAll((StatisticResults result) => result.sampleId == sample.guid);
		foreach (IsotopeInfos isotope2 in Isotopes)
		{
			for (int num2 = 0; num2 < sample.mains; num2++)
			{
				Results.Add(new AnalyseInfos
				{
					isotopeId = isotope2.id,
					symbol = isotope2.symbol,
					sampleId = sample.guid,
					label = sample.label,
					number = num2,
					test = false,
					intensity = -1.0,
					concentration = -1.0,
					icps = -1.0
				});
			}
			Statistics.Add(new StatisticResults
			{
				isotopeId = isotope2.id,
				symbol = isotope2.symbol,
				sampleId = sample.guid,
				label = sample.label,
				avgCon = -1.0,
				avgUICPS = -1.0,
				avgCPS = -1.0,
				sdCon = -1.0,
				sdUICPS = -1.0,
				sdCPS = -1.0,
				rsdCon = -1.0,
				rsdUICPS = -1.0,
				rsdCPS = -1.0,
				include = true
			});
		}
		RatioResults.RemoveAll((RatioResults ratio) => ratio.SampleId == sample.guid);
		RatioStat.RemoveAll((RatioStatistics ratio) => ratio.SampleId == sample.guid);
		foreach (IsotopeRatio isotope in Ratios)
		{
			ratioStat.Add(new RatioStatistics
			{
				Name = isotope.Name,
				Numerator = isotope.NumeratorSym,
				Denominator = isotope.DenominatorSym,
				SampleId = sample.guid,
				Label = sample.label,
				Sd = -1.0,
				Rsd = -1.0,
				Avg = -1.0
			});
			for (int num = 0; num < sample.mains; num++)
			{
				ratioResults.Add(new RatioResults
				{
					Name = isotope.Name,
					Numerator = isotope.NumeratorSym,
					Denominator = isotope.DenominatorSym,
					SampleId = sample.guid,
					Label = sample.label,
					Number = num,
					Result = -1.0
				});
			}
		}
	}

	private void InitSpectrum(SamplesInfos sample)
	{
		timeSpectrums.RemoveAll((TimeSpectrum spectrum) => spectrum.SampleId == sample.guid);
		foreach (IsotopeInfos isotope in isotopes)
		{
			for (int i = 0; i < sample.mains; i++)
			{
				timeSpectrums.Add(new TimeSpectrum
				{
					SampleId = sample.guid,
					SampleLabel = sample.label,
					IsotopeId = isotope.id,
					Symbol = isotope.symbol,
					RunIndex = i,
					isTest = false
				});
			}
		}
	}

	private void SetPeakJumpRegions()
	{
		PeakRegions.Clear();
		foreach (IsotopeInfos isotope in Isotopes)
		{
			PeakRegions.Add(new PeakRegions(isotope.symbol, isotope.mass));
		}
	}

	public bool PreRun()
	{
		if (!InitRunMass())
		{
			MessageBox.Show(Lang.Txt("LA300.Text20"), Lang.Txt("AddFormRatio.Warn"), MessageBoxButtons.OK);
			return false;
		}
		return true;
	}

	public void StartRun()
	{
		IsRun = true;
		SetPeakJumpRegions();
		InitRunMass();
		InitCurve();
		Detector.Instance.ExperimentState = 5;
		Detector.finishReceive += Detector_massFinishReceive;
		Scan.currentStatus = 1;
		if (this.applyEnable != null)
		{
			this.applyEnable(this, null);
		}
		Task.Factory.StartNew(RunExperiment);
	}

	private void Detector_errorReceive(object sender, ErrorMsgEventArgs e)
	{
		LensManager.x2lens.Etp = 0.0;
		LensManager.Instance.SetEtp();
		StopRun();
	}

	public void StopRun(bool stopApply = true)
	{
		if (IsRun)
		{
			IsRun = false;
			SerialCom.Serial.Stop();
			scanEvent.Set();
			Detector.finishReceive -= Detector_massFinishReceive;
			Detector.Instance.Stop();
			if (stopApply)
			{
				Scan.currentStatus = 2;
			}
			else
			{
				Scan.currentStatus = 3;
			}
			Detector.Instance.ExperimentState = -1;
		}
	}

	public void RunExperiment()
	{
		bool acqError = false;
		scanEvent.Reset();
		while (IsRun)
		{
			IEnumerable<SamplesInfos> ss = Samples.Where((SamplesInfos s) => s.status != 1);
			if (ss.Count() > 0)
			{
				if (!IsRun)
				{
					break;
				}
				SamplesInfos currentSample = ss.First();
				if (!ExperimentPrepare(currentSample))
				{
					break;
				}
				Thread.Sleep(1000);
				MyTimers.timeBeginPeriod(1);
				acqError = !ExperimentMainRun(currentSample);
				if (acqError)
				{
					break;
				}
				MyTimers.timeEndPeriod(1);
				currentSample.status = 1;
			}
			else
			{
				StopRun(stopApply: false);
			}
		}
		StopRun();
		if (this.EventExperiment != null)
		{
			this.EventExperiment(null, new ExperimentEventArgs(null, acqError ? (-1) : 3, 0, 0));
		}
	}

	private bool ExperimentPrepare(SamplesInfos currentSample)
	{
		if (this.EventExperiment != null)
		{
			this.EventExperiment(null, new ExperimentEventArgs(currentSample, 0, 0, 0));
		}
		if (!IsRun || !FormExperiment.IsRun)
		{
			return false;
		}
		currentSample.time = DateTime.Now;
		currentSample.status = -1;
		InitResult(currentSample);
		InitSpectrum(currentSample);
		return true;
	}

	private bool ExperimentMainRun(SamplesInfos currentSample)
	{
		IEnumerable<AcqTime> acqInfos = acqTimes.Where((AcqTime acq) => acq.SampleId == currentSample.guid);
		int acqTime = 60;
		int acqSweep = 20;
		if (acqInfos.Any())
		{
			acqTime = acqInfos.First().Time;
			acqSweep = acqInfos.First().Sweeps;
		}
		for (int runIndex = 0; runIndex < currentSample.mains; runIndex++)
		{
			if (this.EventExperiment != null)
			{
				this.EventExperiment(null, new ExperimentEventArgs(currentSample, 4, runIndex, 0));
			}
			while (!SerialCom.Serial.Wait())
			{
				if (!IsRun)
				{
					return false;
				}
				if (MessageBox.Show(Lang.Txt("LA300.Text21"), Lang.Txt("AddFormRatio.Warn"), MessageBoxButtons.YesNo) == DialogResult.No)
				{
					return false;
				}
				if (!IsRun)
				{
					return true;
				}
			}
			if (this.EventExperiment != null)
			{
				this.EventExperiment(null, new ExperimentEventArgs(currentSample, 1, runIndex, 0));
			}
			if (this.EventExperiment != null)
			{
				this.EventExperiment(null, new ExperimentEventArgs(currentSample, 5, runIndex, 0));
			}
			double time = 0.0;
			uint tstart = MyTimers.timeGetTime();
			while (true)
			{
				if (!IsRun)
				{
					return true;
				}
				time = (double)(MyTimers.timeGetTime() - tstart) / 1000.0;
				if (this.EventExperiment != null)
				{
					this.EventExperiment(null, new ExperimentEventArgs(currentSample, 2, runIndex, (int)time));
				}
				for (int sweepIndex = 0; sweepIndex < acqSweep; sweepIndex++)
				{
					if (!IsRun)
					{
						return true;
					}
					if (sweepIndex == 0)
					{
						Detector.Instance.SetMassAxis(peakMass.ToArray());
					}
					Detector.Instance.SetHopDatas(peakMass.ToArray(), (double[])null, resolutionType, true, false);
					if (!scanEvent.WaitOne(60000))
					{
						Log.InsertLog(Lang.Txt("LA300.Text22"), Lang.Txt("LA300.Text23"), Lang.Txt("LA300.Text24"), (Severity)3);
						return false;
					}
				}
				if (SerialCom.bStop)
				{
					break;
				}
				SpectrumInfos currentSpectrum = new SpectrumInfos
				{
					sampleId = currentSample.guid
				};
				ProcessSpectums(currentSpectrum, acqSweep);
				ProcessMainRunDatas(currentSpectrum, runIndex, time);
				if (this.SingleAcq != null)
				{
					this.SingleAcq.BeginInvoke(null, new CurveInfoEventArgs(currentSample.guid, runIndex), null, null);
				}
			}
		}
		currentSample.status = 1;
		return true;
	}

	private void Detector_massFinishReceive(object sender, EventArgs e)
	{
		scanEvent.Set();
	}

	private void ProcessSpectums(SpectrumInfos spectrum, int sweeps)
	{
		int nlenth = Detector.msDetectorPara.Mass.Length;
		spectrum.mass = new double[nlenth];
		spectrum.intensityAnalog = new double[nlenth];
		spectrum.intensityPulse = new double[nlenth];
		spectrum.intensity = new double[nlenth];
		Array.Copy(Detector.msDetectorPara.Mass, spectrum.mass, nlenth);
		for (int i = 0; i < nlenth; i++)
		{
			double pafactor = Detector.Instance.dacPAFactors[(int)(spectrum.mass[i] * 100.0)];
			spectrum.intensityAnalog[i] = Detector.msDetectorPara.IntesnsityAnalog[i] / (double)sweeps;
			spectrum.intensityPulse[i] = Detector.msDetectorPara.IntesnsityPulse[i] / (double)sweeps;
			if (Detector.detectorConfig.IsNewBoard)
			{
				spectrum.intensity[i] = ((spectrum.intensityAnalog[i] > Detector.detectorConfig.PaThreshold) ? (spectrum.intensityAnalog[i] * pafactor + Detector.detectorConfig.DetectorB) : spectrum.intensityPulse[i]);
			}
			else
			{
				spectrum.intensity[i] = ((spectrum.intensityPulse[i] < Detector.detectorConfig.PaThreshold) ? spectrum.intensityPulse[i] : spectrum.intensityAnalog[i]);
			}
		}
	}

	private void ProcessMainRunDatas(SpectrumInfos spectrum, int mainIndex, double time)
	{
		foreach (IsotopeInfos isotope in Isotopes)
		{
			double left = isotope.mass - 0.45;
			double right = isotope.mass + 0.55;
			double[] mass = spectrum.mass;
			double[] intensity = spectrum.intensity;
			double cps = intensity.Where((double data, int index) => mass[index] >= left && mass[index] <= right).Average();
			IEnumerable<TimeSpectrum> tspectrums = timeSpectrums.Where((TimeSpectrum tspectrum) => tspectrum.SampleId == spectrum.sampleId && tspectrum.RunIndex == mainIndex && tspectrum.Symbol == isotope.symbol);
			if (tspectrums.Any())
			{
				TimeSpectrum tspectrum2 = tspectrums.First();
				lock (tspectrum2)
				{
					tspectrum2.Time.Add(time);
					tspectrum2.Intensity.Add(cps);
				}
				tspectrum2.isTest = true;
			}
		}
	}

	private void CalculateIntegerationCPS(SamplesInfos sample)
	{
		if (sample.status != 1)
		{
			return;
		}
		IEnumerable<IntegerRegions> regionsAll = integerRegions.Where((IntegerRegions region) => region.SampleId == sample.guid);
		if (!regionsAll.Any())
		{
			return;
		}
		foreach (IsotopeInfos isotope in isotopes)
		{
			int i;
			for (i = 0; i < sample.mains; i++)
			{
				IEnumerable<TimeSpectrum> tspectrums = timeSpectrums.Where((TimeSpectrum tspectrum) => tspectrum.SampleId == sample.guid && tspectrum.Symbol == isotope.symbol && tspectrum.RunIndex == i && tspectrum.isTest);
				IEnumerable<AnalyseInfos> results = Results.Where((AnalyseInfos result) => result.sampleId == sample.guid && result.symbol == isotope.symbol && result.number == i);
				if (!tspectrums.Any() || !results.Any())
				{
					continue;
				}
				TimeSpectrum tspectrum2 = tspectrums.First();
				double[] time;
				double[] intensity;
				lock (tspectrum2)
				{
					time = tspectrum2.Time.ToArray();
					intensity = tspectrum2.Intensity.ToArray();
				}
				if (time == null || time.Count() <= 0)
				{
					continue;
				}
				AnalyseInfos result2 = results.First();
				double sum = 0.0;
				IEnumerable<IntegerRegions> regions = regionsAll.Where((IntegerRegions r) => r.Mains == i + 1);
				if (!regions.Any())
				{
					continue;
				}
				IntegerRegions region2 = regions.First();
				int start = 0;
				int end = time.Length - 1;
				for (int idx2 = 0; idx2 < time.Length; idx2++)
				{
					if (time[idx2] >= (double)region2.Start)
					{
						start = idx2;
						break;
					}
				}
				for (int idx = time.Length - 1; idx >= 0; idx--)
				{
					if (time[idx] <= (double)region2.End)
					{
						end = idx;
						break;
					}
				}
				sum = (result2.intensity = CalculateIntegerValue(time, intensity, start, end));
				result2.icps = sum;
				result2.test = true;
			}
		}
	}

	private void CalculateUncorrectCPS(IsotopeInfos isotope)
	{
		foreach (StatisticResults stat in Statistics.Where((StatisticResults statistic) => statistic.symbol == isotope.symbol))
		{
			IEnumerable<double> cpss = from result in Results
				where result.symbol == isotope.symbol && result.sampleId == stat.sampleId && result.test && !result.exclude
				select result.intensity;
			if (cpss != null && cpss.Count() > 0)
			{
				stat.avgUICPS = CalculateAverage(cpss.ToArray());
				stat.sdUICPS = CalculateDeviation(cpss.ToArray());
				stat.rsdUICPS = stat.sdUICPS / stat.avgUICPS * 100.0;
			}
		}
	}

	public List<double> CalculateTimeSpectrumConcentration(List<double> intensitys, SamplesInfos sample, IsotopeInfos isotope, int runindex)
	{
		IEnumerable<SamplesInfos> blkSamples = samples.Where((SamplesInfos s) => s.guid == sample.blank);
		if (blkSamples.Any())
		{
			SamplesInfos blkSample = blkSamples.First();
			if (blkSample.status == 1 && sample.status == 1)
			{
				StatisticResults blkStat = statistics.Where((StatisticResults stat) => stat.sampleId == sample.guid && stat.symbol == isotope.symbol).First();
				if (!(blkStat.avgUICPS < 0.0) && !double.IsNaN(blkStat.avgUICPS))
				{
					for (int k = 0; k < intensitys.Count(); k++)
					{
						intensitys[k] -= blkStat.avgUICPS;
					}
				}
			}
		}
		IEnumerable<IsotopeInfos> istds = isotopes.Where((IsotopeInfos istd) => istd.inter);
		if (istds.Any())
		{
			AnalyseInfos istdResult = results.Where((AnalyseInfos result) => result.sampleId == sample.guid && result.symbol == istds.First().symbol && result.number == runindex).First();
			for (int j = 0; j < intensitys.Count(); j++)
			{
				intensitys[j] /= istdResult.icps;
			}
		}
		if (isotope.equations != null && sample.status == 1)
		{
			for (int i = 0; i < intensitys.Count(); i++)
			{
				intensitys[i] = InterferenceValue(intensitys[i], isotope.symbol, sample.guid, runindex);
			}
		}
		return intensitys;
	}

	private void CalculateISTD(IsotopeInfos isotope)
	{
		if (!isotope.inter)
		{
			return;
		}
		foreach (SamplesInfos sample in samples)
		{
			if (sample.status != 1)
			{
				continue;
			}
			IEnumerable<SampleISTD> istdCons = sampleIstds.Where((SampleISTD istdCon) => istdCon.SampleId == sample.guid);
			IEnumerable<AnalyseInfos> destResults = Results.Where((AnalyseInfos result) => result.sampleId == sample.guid && result.symbol == isotope.symbol);
			foreach (AnalyseInfos result2 in destResults)
			{
				result2.concentration = istdCons.First().Concentration;
				result2.icps = result2.concentration / result2.intensity;
			}
		}
	}

	private void CalculateBlankCPS(SamplesInfos sample)
	{
		IEnumerable<SamplesInfos> blkSamples = samples.Where((SamplesInfos s) => s.guid == sample.blank);
		if (!blkSamples.Any())
		{
			return;
		}
		SamplesInfos blkSample = blkSamples.First();
		if (blkSample.status != 1 || sample.status != 1)
		{
			return;
		}
		foreach (IsotopeInfos isotope in isotopes)
		{
			StatisticResults blkStat = statistics.Where((StatisticResults stat) => stat.sampleId == sample.guid && stat.symbol == isotope.symbol).First();
			if (blkStat.avgUICPS < 0.0 || double.IsNaN(blkStat.avgUICPS))
			{
				continue;
			}
			IEnumerable<AnalyseInfos> destResults = results.Where((AnalyseInfos result) => result.sampleId == sample.guid && result.symbol == isotope.symbol);
			foreach (AnalyseInfos result2 in destResults)
			{
				result2.icps = result2.intensity - blkStat.avgUICPS;
			}
		}
	}

	private void CalculateCorrectCPS(SamplesInfos sample, IsotopeInfos istd)
	{
		if (sample.status != 1)
		{
			return;
		}
		int i;
		for (i = 0; i < sample.mains; i++)
		{
			AnalyseInfos istdResult = results.Where((AnalyseInfos result) => result.sampleId == sample.guid && result.symbol == istd.symbol && result.number == i).First();
			IEnumerable<AnalyseInfos> destResults = results.Where((AnalyseInfos result) => result.sampleId == sample.guid && result.number == i && result.symbol != istd.symbol);
			foreach (AnalyseInfos result2 in destResults)
			{
				if (result2.icps != -1.0 || istdResult.icps != -1.0)
				{
					result2.icps /= istdResult.icps;
				}
			}
		}
	}

	private void CalculateInterferenceCPS(IsotopeInfos isotope)
	{
		if (isotope.equations == null)
		{
			return;
		}
		foreach (SamplesInfos sample in Samples)
		{
			if (sample.status != 1)
			{
				continue;
			}
			IEnumerable<AnalyseInfos> cpsResult = Results.Where((AnalyseInfos result) => result.symbol == isotope.symbol && result.sampleId == sample.guid);
			foreach (AnalyseInfos result2 in cpsResult)
			{
				result2.icps = InterferenceValue(result2.symbol, result2.sampleId, result2.number);
			}
		}
	}

	private double InterferenceValue(string symbol, int sampleId, int number)
	{
		IsotopeInfos currentIsotope = Isotopes.Find((IsotopeInfos isotope) => isotope.symbol == symbol);
		double icps = 0.0;
		IEnumerable<AnalyseInfos> results = Results.Where((AnalyseInfos result) => result.symbol == symbol && result.sampleId == sampleId && result.number == number);
		if (results != null && results.Count() > 0)
		{
			AnalyseInfos result2 = results.First();
			if (currentIsotope.equations != null && !result2.interferenceCorrected)
			{
				foreach (InterferenceEquation equation in currentIsotope.equations)
				{
					result2.icps += equation.interferenceFactor * InterferenceValue(equation.interferenceSymbol, sampleId, number);
				}
				result2.interferenceCorrected = true;
			}
			icps = result2.icps;
		}
		return icps;
	}

	private double InterferenceValue(double icps, string symbol, int sampleId, int number)
	{
		IsotopeInfos currentIsotope = Isotopes.Find((IsotopeInfos isotope) => isotope.symbol == symbol);
		IEnumerable<AnalyseInfos> results = Results.Where((AnalyseInfos result) => result.symbol == symbol && result.sampleId == sampleId && result.number == number);
		if (results != null && results.Count() > 0)
		{
			AnalyseInfos result2 = results.First();
			if (currentIsotope.equations != null)
			{
				foreach (InterferenceEquation equation in currentIsotope.equations)
				{
					icps += equation.interferenceFactor * InterferenceValue(equation.interferenceSymbol, sampleId, number);
				}
			}
		}
		return icps;
	}

	private void CalculateStatCPS(IsotopeInfos isotope)
	{
		if (isotope.isInterference)
		{
			return;
		}
		foreach (SamplesInfos sample in Samples)
		{
			if (sample.status == 0)
			{
				continue;
			}
			IEnumerable<double> cpss = from result in Results
				where result.symbol == isotope.symbol && result.sampleId == sample.guid && result.test && !result.exclude
				select result.icps;
			if (cpss != null && cpss.Count() > 0)
			{
				double average = CalculateAverage(cpss.ToArray());
				double sd = CalculateDeviation(cpss.ToArray());
				double rsd = sd / average * 100.0;
				StatisticResults statResult = Statistics.Where((StatisticResults stat) => stat.symbol == isotope.symbol && stat.sampleId == sample.guid).First();
				statResult.avgCPS = average;
				statResult.sdCPS = sd;
				statResult.rsdCPS = rsd;
			}
		}
	}

	private void CalculateCurve(IsotopeInfos isotope, bool istd = false)
	{
		if (isotope.inter || isotope.method == 0 || isotope.method == 3)
		{
			return;
		}
		string currentSymbol = isotope.symbol;
		int currentMethod = isotope.method;
		List<StatisticResults> stats = new List<StatisticResults>();
		stats.AddRange(from result in Statistics
			from sample in Samples
			where result.symbol == currentSymbol && result.sampleId == sample.guid && (sample.type == 0 || sample.type == currentMethod) && sample.status == 1
			select result);
		if (stats == null || stats.Count < 2)
		{
			return;
		}
		foreach (StatisticResults stat2 in stats)
		{
			IEnumerable<StandardConcentration> std = StdConcentration.Where((StandardConcentration stdCon) => stdCon.sample == stat2.sampleId && stdCon.symbol == Regex.Replace(stat2.symbol, "[0-9]", "", RegexOptions.IgnoreCase));
			if (std != null && std.Count() > 0)
			{
				stat2.stdCon = std.ElementAt(0).concentration;
			}
		}
		IEnumerable<double> cps1 = from result in stats
			where result.include && result.stdCon >= 0.0
			select result.avgCPS;
		List<double> con1 = new List<double>();
		foreach (StatisticResults stat in stats)
		{
			double stdcon = 0.0;
			if (!stat.include || !(stat.stdCon >= 0.0))
			{
				continue;
			}
			stdcon = stat.stdCon;
			if (istd)
			{
				IEnumerable<IsotopeInfos> istds = isotopes.Where((IsotopeInfos istde) => istde.inter);
				IEnumerable<SampleISTD> istdCons = SampleIstds.Where((SampleISTD istdCon) => istdCon.SampleId == stat.sampleId);
				stdcon /= istdCons.ElementAt(0).Concentration;
			}
			con1.Add(stdcon);
		}
		if (cps1.Count() <= 1 && con1.Count() <= 1)
		{
			return;
		}
		int points = stats.Where((StatisticResults result) => result.stdCon >= 0.0).Count();
		double[] kb = null;
		IEnumerable<StatisticResults> blkResult = from result in stats
			from sample in Samples
			where sample.type == 0 && result.symbol == isotope.symbol && result.sampleId == sample.guid && result.include
			select result;
		if (isotope.force == 2)
		{
			kb = LSFit.LineFit(con1.ToArray(), cps1.ToArray(), 0.0, 0.0, true);
		}
		else if (isotope.force == 1 && blkResult != null && blkResult.Count() != 0)
		{
			kb = LSFit.LineFit(con1.ToArray(), cps1.ToArray(), blkResult.First().stdCon, blkResult.First().avgCPS, true);
		}
		else if (isotope.weight == 0)
		{
			kb = LSFit.LineFit(con1.ToArray(), cps1.ToArray(), 0.0, 0.0, false);
		}
		else
		{
			List<double> weights = new List<double>(con1);
			for (int i = 0; i < weights.Count(); i++)
			{
				if (weights[i] != 0.0)
				{
					weights[i] = 1.0 / Math.Pow(weights[i], 2.0);
				}
			}
			kb = LSFit.WLineFit(con1.ToArray(), cps1.ToArray(), weights.ToArray(), 0.0, 0.0, false);
		}
		if (kb != null)
		{
			IEnumerable<IsotopeCurve> curves = Curves.Where((IsotopeCurve curve) => curve.symbol == currentSymbol);
			if (curves != null && curves.Count() == 1)
			{
				curves.ElementAt(0).method = currentMethod;
				curves.ElementAt(0).k = kb[0];
				curves.ElementAt(0).b = kb[1];
				curves.ElementAt(0).r = kb[2];
				curves.ElementAt(0).intercept1 = Math.Abs(kb[1]);
				curves.ElementAt(0).intercept2 = Math.Abs(kb[1] / kb[0]);
				curves.ElementAt(0).calculated = true;
				curves.ElementAt(0).points = points;
				Dirty.CurveDirty = true;
			}
		}
	}

	private void CalculateCon(SamplesInfos sample, bool istd = false)
	{
		if (sample.status != 1)
		{
			return;
		}
		foreach (IsotopeCurve curve in Curves)
		{
			if (!curve.calculated)
			{
				continue;
			}
			IEnumerable<AnalyseInfos> conResult = Results.Where((AnalyseInfos result) => result.sampleId == sample.guid && result.symbol == curve.symbol);
			List<double> cons2 = new List<double>();
			foreach (AnalyseInfos con in conResult)
			{
				double blkCPS = 0.0;
				if (curve.method == 2)
				{
					con.concentration = (con.icps - blkCPS) / curve.k * sample.predilution;
					con.concentration = ((con.concentration < 0.0) ? 0.0 : con.concentration);
				}
				else if (curve.method == 1)
				{
					con.concentration = (con.icps - blkCPS - curve.b) / curve.k;
					con.concentration = ((con.concentration < 0.0) ? 0.0 : (con.concentration * sample.predilution));
				}
				if (!con.exclude)
				{
					cons2.Add(con.concentration);
				}
			}
			if (cons2 != null && cons2.Count() > 0)
			{
				double average = CalculateAverage(cons2.ToArray());
				double sd = CalculateDeviation(cons2.ToArray());
				double rsd = sd / average * 100.0;
				average = ((average < 0.0) ? 0.0 : average);
				sd = ((sd < 0.0) ? 0.0 : sd);
				rsd = ((rsd < 0.0) ? 0.0 : rsd);
				StatisticResults stat3 = Statistics.Where((StatisticResults statistic) => statistic.symbol == curve.symbol && statistic.sampleId == sample.guid).First();
				stat3.avgCon = average;
				stat3.sdCon = sd;
				stat3.rsdCon = rsd;
			}
		}
		double stdcon = 1.0;
		IEnumerable<IsotopeInfos> istds = isotopes.Where((IsotopeInfos istde) => istde.inter);
		if (istds.Any())
		{
			List<double> ss = new List<double>();
			IEnumerable<StatisticResults> results = statistics.Where((StatisticResults result) => result.symbol != istds.First().symbol && result.sampleId == sample.guid);
			foreach (StatisticResults result2 in results)
			{
				ss.Add(result2.avgCon);
			}
			stdcon = 100.0 / (1.0 + ss.Sum());
			IEnumerable<StatisticResults> istdresults = statistics.Where((StatisticResults result) => result.symbol == istds.First().symbol && result.sampleId == sample.guid);
			istdresults.First().avgCon = stdcon;
			IEnumerable<AnalyseInfos> istdsingleresult = Results.Where((AnalyseInfos result) => result.symbol == istds.First().symbol && result.sampleId == sample.guid);
			double sum = 0.0;
			List<double> cons = new List<double>();
			foreach (AnalyseInfos singleresult2 in istdsingleresult)
			{
				sum += singleresult2.icps;
			}
			foreach (AnalyseInfos singleresult in istdsingleresult)
			{
				singleresult.concentration = singleresult.icps / sum * stdcon * (double)istdsingleresult.Count();
				cons.Add(singleresult.concentration);
			}
			istdresults.First().sdCon = CalculateDeviation(cons.ToArray());
			istdresults.First().rsdCon = istdresults.First().sdCon / istdresults.First().avgCon * 100.0;
		}
		IEnumerable<AnalyseInfos> Resultcon = Results.Where((AnalyseInfos result) => result.sampleId == sample.guid && (!istds.Any() || result.symbol != istds.First().symbol));
		foreach (AnalyseInfos item in Resultcon)
		{
			item.concentration *= stdcon;
		}
		IEnumerable<StatisticResults> stats = statistics.Where((StatisticResults stat) => stat.sampleId == sample.guid && (!istds.Any() || stat.symbol != istds.First().symbol));
		foreach (StatisticResults stat2 in stats)
		{
			stat2.avgCon *= stdcon;
			stat2.sdCon *= stdcon;
			stat2.rsdCon = stat2.rsdCon;
		}
	}

	private void CalculateRatio(SamplesInfos sample)
	{
		if (sample.status != 1)
		{
			return;
		}
		IEnumerable<RatioResults> results = ratioResults.Where((RatioResults result) => result.SampleId == sample.guid);
		foreach (RatioResults result2 in results)
		{
			IEnumerable<double> numerator = from cps in Results
				where cps.sampleId == sample.guid && cps.symbol == result2.Numerator && cps.number == result2.Number
				select cps.icps;
			IEnumerable<double> denominator = from cps in Results
				where cps.sampleId == sample.guid && cps.symbol == result2.Denominator && cps.number == result2.Number
				select cps.icps;
			result2.Result = numerator.First() / denominator.First();
		}
		IEnumerable<RatioStatistics> statistics = RatioStat.Where((RatioStatistics stat) => stat.SampleId == sample.guid);
		foreach (RatioStatistics stat2 in statistics)
		{
			IEnumerable<double> rs = from result in ratioResults
				where result.Name == stat2.Name && result.SampleId == sample.guid
				select result.Result;
			if (rs != null && rs.Count() > 0)
			{
				stat2.Avg = CalculateAverage(rs.ToArray());
				stat2.Sd = CalculateDeviation(rs.ToArray());
				stat2.Rsd = stat2.Sd / stat2.Avg * 100.0;
			}
		}
	}

	public void RecalculatedAll()
	{
		if (isInCalculate)
		{
			return;
		}
		isInCalculate = true;
		foreach (SamplesInfos sample5 in samples)
		{
			CalculateIntegerationCPS(sample5);
		}
		foreach (IsotopeInfos isotope4 in isotopes)
		{
			CalculateUncorrectCPS(isotope4);
		}
		foreach (SamplesInfos sample4 in samples)
		{
			CalculateBlankCPS(sample4);
		}
		IEnumerable<IsotopeInfos> istds = isotopes.Where((IsotopeInfos istd) => istd.inter);
		if (istds.Any())
		{
			foreach (SamplesInfos sample3 in samples)
			{
				CalculateCorrectCPS(sample3, istds.First());
			}
		}
		SetUnCalculateInterference();
		foreach (IsotopeInfos isotope3 in isotopes)
		{
			CalculateInterferenceCPS(isotope3);
		}
		foreach (IsotopeInfos isotope2 in isotopes)
		{
			CalculateStatCPS(isotope2);
		}
		foreach (IsotopeInfos isotope in Isotopes)
		{
			CalculateCurve(isotope, istds.Any());
		}
		foreach (SamplesInfos sample2 in Samples)
		{
			CalculateCon(sample2, istds.Any());
		}
		foreach (SamplesInfos sample in Samples)
		{
			CalculateRatio(sample);
		}
		isInCalculate = false;
		Dirty.ResultsDirty = true;
	}

	private void SetUnCalculateInterference()
	{
		IEnumerable<AnalyseInfos> results = from result in Results
			from isotope in Isotopes
			where result.symbol == isotope.symbol && isotope.withInterference
			select result;
		foreach (AnalyseInfos result2 in results)
		{
			result2.interferenceCorrected = false;
		}
	}

	private double CalculateAverage(double[] values)
	{
		if (values != null && values.Length != 0)
		{
			return values.Average();
		}
		return double.NaN;
	}

	private double CalculateDeviation(double[] values)
	{
		if (values == null)
		{
			return double.NaN;
		}
		double sum = 0.0;
		double sum2 = 0.0;
		int counter = 0;
		foreach (double val in values)
		{
			if (!double.IsNaN(val))
			{
				sum += val;
				sum2 += val * val;
				counter++;
			}
		}
		if (counter < 2)
		{
			return double.NaN;
		}
		return Math.Sqrt(((double)counter * sum2 - sum * sum) / (double)counter / (double)(counter - 1));
	}

	public void CalculateCurve(string symbol)
	{
		IEnumerable<IsotopeInfos> isos = Isotopes.Where((IsotopeInfos isotope) => isotope.symbol == symbol);
		IEnumerable<IsotopeInfos> istds = isotopes.Where((IsotopeInfos istd) => istd.inter);
		if (isos != null && isos.Count() > 0)
		{
			CalculateCurve(isos.ElementAt(0), istds.Any());
		}
	}

	public void ChangeSampleLabel(SamplesInfos sample)
	{
		string label = sample.label;
		IEnumerable<StatisticResults> stats = Statistics.Where((StatisticResults statistic) => statistic.sampleId == sample.guid);
		foreach (StatisticResults stat in stats)
		{
			stat.label = label;
		}
		IEnumerable<AnalyseInfos> results = Results.Where((AnalyseInfos result) => result.sampleId == sample.guid);
		foreach (AnalyseInfos result2 in results)
		{
			result2.label = label;
		}
		IEnumerable<StandardConcentration> stds = StdConcentration.Where((StandardConcentration stdCon) => stdCon.sample == sample.guid);
		foreach (StandardConcentration std in stds)
		{
			std.label = label;
		}
		IEnumerable<SampleISTD> sistds = sampleIstds.Where((SampleISTD istds) => istds.SampleId == sample.guid);
		foreach (SampleISTD sistd in sistds)
		{
			sistd.SampleName = label;
		}
		IEnumerable<AcqTime> acqs = acqTimes.Where((AcqTime acq) => acq.SampleId == sample.guid);
		foreach (AcqTime acq2 in acqs)
		{
			acq2.SampleName = label;
		}
		IEnumerable<TimeSpectrum> tspectrums = timeSpectrums.Where((TimeSpectrum spectrum) => spectrum.SampleId == sample.guid);
		foreach (TimeSpectrum spectrum2 in tspectrums)
		{
			spectrum2.SampleLabel = label;
		}
		Dirty.SamplesDirty = true;
	}

	public void CheckReferSample(int rowIndex = -1)
	{
		if (Samples.Count == 0)
		{
			return;
		}
		if (rowIndex == -1)
		{
			IEnumerable<SamplesInfos> refers = Samples.Where((SamplesInfos sample) => sample.refer);
			if (refers.Count() == 0)
			{
				Samples[0].refer = true;
			}
			return;
		}
		foreach (SamplesInfos sample2 in Samples)
		{
			sample2.refer = false;
		}
		Samples[rowIndex].refer = true;
	}

	public void CheckISTDCurve()
	{
		foreach (IsotopeCurve curve in Curves)
		{
			foreach (IsotopeInfos isotope in Isotopes)
			{
				if (curve.symbol == isotope.symbol)
				{
					if (isotope.inter)
					{
						curve.calculated = false;
					}
					break;
				}
			}
		}
	}

	public void SetResultExclude(string symbol, int sampleId, int num, bool exclude)
	{
		IEnumerable<AnalyseInfos> results = Results.Where((AnalyseInfos result) => result.symbol == symbol && result.sampleId == sampleId && result.number == num);
		if (results != null && results.Count() > 0)
		{
			results.ElementAt(0).exclude = exclude;
		}
	}

	public void SetUnTested()
	{
		foreach (AnalyseInfos result in Results)
		{
			result.SetUnTested();
		}
		foreach (StatisticResults stat in Statistics)
		{
			stat.SetUnTested();
		}
		foreach (SamplesInfos sample in Samples)
		{
			sample.SetUnTested();
		}
		foreach (IsotopeCurve curve in Curves)
		{
			curve.SetUnTested();
		}
		foreach (RatioResults ratio in RatioResults)
		{
			ratio.SetUnTested();
		}
		foreach (TimeSpectrum spectrum in timeSpectrums)
		{
			spectrum.SetUnTest();
		}
		Scan.SetUnTested();
	}

	public bool IsISTD(string symbol)
	{
		foreach (IsotopeInfos isotope in Isotopes)
		{
			if (isotope.symbol == symbol && isotope.inter)
			{
				return true;
			}
		}
		return false;
	}

	public void SetupISTDbySamples()
	{
		sampleIstds.RemoveAll((SampleISTD istd) => !samples.Exists((SamplesInfos sample) => sample.guid == istd.SampleId));
		foreach (SamplesInfos sample2 in samples)
		{
			if (!sampleIstds.Exists((SampleISTD istd) => istd.SampleId == sample2.guid))
			{
				sampleIstds.Add(new SampleISTD
				{
					SampleId = sample2.guid,
					SampleName = sample2.label,
					Concentration = 0.0,
					Unit = 0
				});
			}
		}
	}

	public void SetupSampleAcqTimes()
	{
		acqTimes.RemoveAll((AcqTime acq) => !samples.Exists((SamplesInfos sample) => sample.guid == acq.SampleId));
		List<AcqTime> acqs = new List<AcqTime>();
		foreach (SamplesInfos sample2 in samples)
		{
			AcqTime acq2 = new AcqTime
			{
				SampleId = sample2.guid,
				SampleName = sample2.label
			};
			AcqTime tacq = acqTimes.Find((AcqTime a) => a.SampleId == sample2.guid);
			if (tacq != null)
			{
				acq2.Time = tacq.Time;
				acq2.Sweeps = tacq.Sweeps;
			}
			acqs.Add(acq2);
		}
		acqTimes.Clear();
		acqTimes.AddRange(acqs);
	}

	private double CalculateIntegerValue(double[] time, double[] intensity, int start, int end)
	{
		if (time == null || end == start)
		{
			return 0.0;
		}
		double sum = 0.0;
		for (int i = start; i <= end - 1; i++)
		{
			sum += (intensity[i + 1] + intensity[i]) * (time[i + 1] - time[i]) / 2.0;
		}
		return sum / (time[end] - time[start]);
	}

	public void OnIsotopeChanged()
	{
		SortIsotopes();
		if (this.isotopeChanged != null)
		{
			this.isotopeChanged(null, null);
		}
	}

	public void OnIstdChanged()
	{
		CheckISTDCurve();
		if (this.istdChanged != null)
		{
			this.istdChanged(null, null);
		}
	}

	public void OnSampleChanged()
	{
		Dirty.SamplesDirty = true;
		if (this.sampleChanged != null)
		{
			this.sampleChanged(null, null);
		}
	}

	public void OnMethodChanged()
	{
		CheckISTDCurve();
		if (this.methodChanged != null)
		{
			this.methodChanged(null, null);
		}
	}
}
